package com.gengzp.rpc.core.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gengzp.rpc.core.RpcRemoteTransactionRollbackProcessor;
import com.gengzp.rpc.core.RpcRequestIdentificationCoreFunc;
import com.gengzp.rpc.exception.RpcException;
import com.gengzp.rpc.model.common.resp.RpcResponse;
import com.gengzp.rpc.model.remoteTransaction.req.RpcRollbackRequest;
import com.gengzp.rpc.tools.RpcHttpRequester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.gengzp.rpc.constants.RpcRequestCodeConstants.RPC_REQUEST_SUCCESS;

/**
 * @ClassName RpcRemoteTransactionRollbackProcessorDefaultImpl
 * @Description rpc框架远程事务回滚处理器默认实现类
 * @Author gengzp
 * @Date 2025/8/25 14:18
 */
@Component
public class RpcRemoteTransactionRollbackProcessorDefaultImpl implements RpcRemoteTransactionRollbackProcessor {

    @Override
    public void doRollbackRemoteTransaction(String requestUrl,
                                            Map<String, String> requestHeader,
                                            RpcRollbackRequest rollbackReq) throws RpcException {
        try {
            RpcResponse<Object> rpcResponse = RpcHttpRequester.post(requestUrl, rollbackReq, requestHeader, new TypeReference<>() {
            });
            if (rpcResponse == null || RPC_REQUEST_SUCCESS != rpcResponse.getCode()) {
                throw RpcException.get(rpcResponse == null ? "未获取到回滚调用信息" : rpcResponse.getMessage());
            }
        } catch (Exception e) {
            // 回滚调用失败, 则不清除远程事务缓存
            throw RpcException.get(String.format("远程事务回滚失败, 错误信息: %s", e.getMessage()));
        }
    }

}
